# -*- coding: utf-8 -*-

import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests
from urllib.parse import  urlencode
from threading import Thread

class Spider(object):

    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "泰康欣悦人生保险产品计划"
    # 生成产品数据
    def genProductInfo(self):
        plan = {

            "planA":{
                # 年龄段
                "year":[i for i in range(18,46)],
                #性别
                "gender":["M","F"],
                #保额
                "money":["50000","100000","150000","200000","300000","500000"],
                #交费间隔
                "interval":["0"],
                #交费方式
                "payType":["一次交清"],
                #保障期限
                "expire":["60岁"],
                #投保对象
                "payObject":["本人/儿女/父母/配偶"]
            },
            "planB": {
                # 年龄段
                "year": [i for i in range(18, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["5"],
                # 交费方式
                "payType": ["年交","月交"],
                # 保障期限
                "expire": ["60岁"],
                # 投保对象
                "payObject": ["本人/儿女/父母/配偶"]
            },
            "planC": {
                # 年龄段
                "year": [i for i in range(18, 45)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["10"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 保障期限
                "expire": ["60岁"],
                # 投保对象
                "payObject": ["本人/儿女/父母/配偶"]
            },
            "planD": {
                # 年龄段
                "year": [i for i in range(18, 42)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["15"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 保障期限
                "expire": ["60岁"],
                # 投保对象
                "payObject": ["本人/儿女/父母/配偶"]
            },
            "planE": {
                # 年龄段
                "year": [i for i in range(18, 49)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["20"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 保障期限
                "expire": ["60岁"],
                # 投保对象
                "payObject": ["本人/儿女/父母/配偶"]
            },
            "planF": {
                # 年龄段
                "year": [i for i in range(18, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["0"],
                # 交费方式
                "payType": ["一次交清"],
                # 保障期限
                "expire": ["70岁"],
                # 投保对象
                "payObject": ["本人/儿女/父母/配偶"]
            },
            "planG": {
                # 年龄段
                "year": [i for i in range(18, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["5","10"],
                # 交费方式
                "payType": ["年交","月交"],
                # 保障期限
                "expire": ["70岁"],
                # 投保对象
                "payObject": ["本人/儿女/父母/配偶"]
            },
            "planH": {
                # 年龄段
                "year": [i for i in range(18, 49)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["15"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 保障期限
                "expire": ["70岁"],
                # 投保对象
                "payObject": ["本人/儿女/父母/配偶"]
            },
            "planI": {
                # 年龄段
                "year": [i for i in range(18, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["20"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 保障期限
                "expire": ["70岁"],
                # 投保对象
                "payObject": ["本人/儿女/父母/配偶"]
            },
            "planJ": {
                # 年龄段
                "year": [i for i in range(18, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["0"],
                # 交费方式
                "payType": ["一次交清"],
                # 保障期限
                "expire": ["80岁"],
                # 投保对象
                "payObject": ["本人/儿女/父母/配偶"]
            },
            "planK": {
                # 年龄段
                "year": [i for i in range(18, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["5","10"],
                # 交费方式
                "payType": ["年交","月交"],
                # 保障期限
                "expire": ["80岁"],
                # 投保对象
                "payObject": ["本人/儿女/父母/配偶"]
            },
            "planL": {
                # 年龄段
                "year": [i for i in range(18, 54)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["15"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 保障期限
                "expire": ["80岁"],
                # 投保对象
                "payObject": ["本人/儿女/父母/配偶"]
            },
            "planM": {
                # 年龄段
                "year": [i for i in range(18, 50)],
                # 性别
                "gender": ["M", "F"],
                # 保额
                "money": ["50000", "100000", "150000", "200000", "300000", "500000"],
                # 交费间隔
                "interval": ["20"],
                # 交费方式
                "payType": ["年交", "月交"],
                # 保障期限
                "expire": ["80岁"],
                # 投保对象
                "payObject": ["本人/儿女/父母/配偶"]
            },

        }
        for k in plan:

            for v in product(plan[k]["year"],plan[k]["gender"],plan[k]["money"],plan[k]["interval"],plan[k]["expire"],plan[k]["payType"],plan[k]["payObject"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0],v[1],v[2],v[3],v[4],v[5],v[6]
                ))

                self.mysql._conn.commit()
                print( domain[self.name]["insert_sql"].format(
                        v[0],v[1],v[2],v[3],v[4],v[5],v[6]
                    ))
    # 执行爬虫
    def requestJson(self, dt=None, mysql=None):

        data = {
            "codeFlag": "0",
            "productNo": "B47",
            "poltype": "01",
            "responsibility": "B47",
            "insuredGender": dt["gender"],
            "birthday": "{0} - 01 - 01".format(str(2020 - int(dt["year"]))),
            "applicantGender": dt["gender"],
            "holderBirthday": "{0} - 01 - 01".format(str(2020 - int(dt["year"]))),
            "paymentDuration": "1" if dt["interval"] == "0" else dt["interval"],
            "paymentMode": "01" if dt["payType"] == "年交" else "12",
            "insureDuration": "" + dt["expire"].replace("岁", "") + "_A",
            "coverageAmount": str(int(int(dt["money"]) / 10000))
        }

        payload = urlencode(data).replace("+", "")

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

        if r.status_code == 200 and "grossFirstPremium" in r.text:
            price = r.json()["grossFirstPremium"]
            data = {
                "name": self.name,
                "id": dt["id"],
                "price": price
            }
            print(data)
            mysql.updatePrice(data)
        else:
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 3
            }
            mysql.updateTask(data)
            print("\n/*产品价格数据更新失败:%d*/" % dt["id"])

    def main(self, mysql):

        while True:

            # 随机领取一条数据
            dt = mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

            # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            mysql.updateTask(data)

            self.requestJson(dt, mysql)

    def startProcess(self):

        for i in range(5):
            mysql = MysqlClient()

            t = Thread(target=self.main, args=(mysql,))

            t.start()
if __name__ == '__main__':
    s = Spider()
    s.startProcess()
